/*
 * @(#) MeetingServiceImpl
 *
 * <br> Copyright:  Copyright (c) 2017
 * <br> @author caijinhuang
 * <br> 2017-12-18 16:02:34
 */

package com.sunsharing.sharemeeting.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunsharing.component.ulynlist.executor.QueryAbstractFilter;
import com.sunsharing.component.ulynlist.model.BusinessData;
import com.sunsharing.component.ulynlist.model.RequestData;
import com.sunsharing.share.common.base.IdGenerator;
import com.sunsharing.sharemeeting.constant.FileUrl;
import com.sunsharing.sharemeeting.dao.api.AttachmentDao;
import com.sunsharing.sharemeeting.dao.api.AttenderDao;
import com.sunsharing.sharemeeting.dao.api.DecisionDao;
import com.sunsharing.sharemeeting.dao.api.DecisionPerformerDao;
import com.sunsharing.sharemeeting.dao.api.MeetingDao;
import com.sunsharing.sharemeeting.dao.api.NoteDao;
import com.sunsharing.sharemeeting.entity.Attachment;
import com.sunsharing.sharemeeting.entity.Attender;
import com.sunsharing.sharemeeting.entity.Decision;
import com.sunsharing.sharemeeting.entity.DecisionPerformer;
import com.sunsharing.sharemeeting.entity.Meeting;
import com.sunsharing.sharemeeting.entity.Note;
import com.sunsharing.sharemeeting.entity.User;
import com.sunsharing.sharemeeting.service.BaseService;
import com.sunsharing.sharemeeting.service.api.MeetingService;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

@Service("meetingService")
public class MeetingServiceImpl extends BaseService implements MeetingService {
    @Resource
    MeetingDao meetingDao;
    @Resource
    DecisionDao decisionDao;
    @Resource
    DecisionPerformerDao decisionPerformerDao;
    @Resource
    AttenderDao attenderDao;
    @Resource
    AttachmentDao attachmentDao;
    @Resource
    NoteDao noteDao;


    /**
     * 保存记录：保存会议记录
     * @param params
     *  参数：
     *      params: {
     *           meetingId:'',//会议id
     *           meetingTitle: '',//会议主题
     *           meetingPlace: '',//会议地点
     *           meetingPresenter: '',//主持人
     *           meetingContent: '',//会议内容
     *           //会议决议
     *           meetingDecision: [{
     *              decisionContent:"",//决议内容
     *              members:[],//决议执行人
     *              decisionEndTime:"",//截至日期
     *              priority:"",//决议优先级
     *           }],
     *              attenderMember: [{userId:'',state:''}],//所有参会人员
     *           },
     * @return 会议Id
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public String saveMeeting(JSONObject params, String userId) {
        boolean isEmpty = true;
        //会议信息
        Meeting meeting = JSON.parseObject(params.toJSONString(), Meeting.class);
        List<DecisionPerformer> decisionPerformerList = new ArrayList<DecisionPerformer>();

        List<Decision> decisionList = new ArrayList<>();
        List<Attender> attenderList = new ArrayList<>();
        meeting.setMeetingUsername(userId);
        meeting.setIsPublic(0);

        //如果没有会议id表示该会议未保存，是新会议，则执行插入操作，如果不为空则执行更新操作
        if (meeting.getMeetingId() == null || meeting.getMeetingId().equals("")) {
            meeting.setMeetingId(IdGenerator.uuid2());
            Date now = new Date();
            meeting.setMeetingTime(now);
            isEmpty = true;
        } else {
            meeting.setIsPublic(1);

            JSONArray arry = params.getJSONArray("meetingDecision");
            JSONArray members = params.getJSONArray("attenderMember");
            decisionList = JSON.parseArray(arry.toJSONString(), Decision.class);
            attenderList = JSON.parseArray(members.toJSONString(), Attender.class);
            //会议决议
            for (Decision decision : decisionList) {
                decision.setNoteDecisionId(IdGenerator.uuid2());
                decision.setMeetingId(meeting.getMeetingId());
                decision.setShareNumber(decision.getMembers().length);//会议指派给几个人就分成几份
                decision.setDecisionEndTime(new Timestamp(decision.getDecisionEndTime().getTime() + 64800000L));
                for (String memberid : decision.getMembers()) {
                    DecisionPerformer decisionPerformer = new DecisionPerformer();
                    decisionPerformer.setNoteDecisionId(decision.getNoteDecisionId());
                    decisionPerformer.setUserId(memberid);
                    decisionPerformer.setRemindTime(decision.getDecisionEndTime());
                    decisionPerformer.setDecisionPerformerId(IdGenerator.uuid2());
                    decisionPerformerList.add(decisionPerformer);
                }
            }
            // 参会人员信息
            for (Attender attender : attenderList) {
                attender.setMeetingId(meeting.getMeetingId());
                attender.setNoteAttenderId(IdGenerator.uuid2());
            }
            isEmpty = false;
        }

        if (isEmpty) {
            meetingDao.insertOneMeeting(meeting);
        } else {
            meetingDao.updateMeeting(meeting);
            if (decisionList.size() != 0) {
                decisionDao.insertDecisions(decisionList);
                decisionPerformerDao.insertDecisionPerformer(decisionPerformerList);
            }
            attenderDao.insertMembers(attenderList);
        }
        return meeting.getMeetingId();
    }

    /**
     * 查询所有会议信息
     * @param userid 用户Id
     * @return
     */
    public List<Meeting> getMeetings(String userid, JSONObject params, String userRole) {
        List<Meeting> meetings = null;
        String title = params.getString("title");
        String isOpen = params.getString("isOpen");
        //判断是否有查询要求
        if (title == null || title.equals("")) {
            /**
             * 0：表示未发布
             * 1：表示已发布
             */
            if (isOpen.equals("1")) {
                if (userRole.equals("super_admin")) {
                    meetings = meetingDao.selectAllMeetings();
                } else {
                    meetings = meetingDao.selectMeetingsById(userid);
                }
            } else if (isOpen.equals("0")) {
                meetings = meetingDao.selectDraftsMeetingsById(userid);
            }
        } else {
            if (userRole.equals("admin") || userRole.equals("super_admin")) {
                meetings = meetingDao.searchMoreMeetings("%" + title + "%");
            } else {
                meetings = meetingDao.searchMeeting("%" + title + "%", userid);
            }
        }
        return meetings;
    }

    /**
     * 分页查询所有会议信息
     * @param user 用户Id
     * @param page 页码
     * @param params = {
     *              title: 会议标题
     *              isOpen: 是否发布
     * } 参数
     * @return
     */
    public List<Meeting> getMeetingByPage(User user, int page, JSONObject params) {
        String title = params.getString("title");
        String isOpen = params.getString("isOpen");

        List<Meeting> meetings = null;
        if (title != null && !title.equals("")) {
            if (user.getRoleName().equals("admin")) {
                meetings = meetingDao.searchAllByPage("%" + title + "%", page);
            } else {
                meetings = meetingDao.searchMeetingByPage(user.getUserId(), "%" + title + "%", page);
            }
        } else if (isOpen != null) {
            if (isOpen.equals("1")) {
                if (user.getRoleName().equals("super_admin")) {
                    meetings = meetingDao.selectAllByPage(page);
                } else {
                    meetings = meetingDao.selectMeetingsByPage(user.getUserId(), page);
                }
            } else {
                meetings = meetingDao.selectDraftsMeetingsByPage(user.getUserId(), page);
            }
        }
        return meetings;
    }


    /**
     * 获取会议信息详情
     * @param meetingId 会议Id
     * @return
     */
    public Meeting getMeetingDetail(String meetingId) {
        Meeting meeting = meetingDao.selectMeetingDetailByMeetingId(meetingId);
        for (int i = 0; i < meeting.getAttenderList().size(); i++) {
            if (meeting.getAttenderList().get(i).getUserId().equals(meeting.getMeetingPresenter())) {
                meeting.setMeetingPresenter(meeting.getAttenderList().get(i).getNickname());
            }
            if (meeting.getAttenderList().get(i).getUserId().equals(meeting.getMeetingUsername())) {
                meeting.setMeetingUsername(meeting.getAttenderList().get(i).getNickname());
            }
        }
        return meeting;
    }

    /**
     * 上传文件
     * @param fileName 文件名称
     * @param meetingId 会议Id
     * @param userId 用户Id
     * @return
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public Map<String, String> uploadFile(List<String> fileName, String meetingId, String userId) {
        List<Attachment> attachmentList = new ArrayList<Attachment>();
        Map<String, String> fileIdList = new HashMap<>();
        for (String name : fileName) {
            Attachment attachment = new Attachment();
            attachment.setMeetingId(meetingId);
            attachment.setUserId(userId);
            attachment.setNoteAttachmentId(IdGenerator.uuid2());
            fileIdList.put(name, attachment.getNoteAttachmentId());
            attachment.setDownloadCount(0);
            attachment.setAttachmentUri(FileUrl.FILEURL + "/" + name);
            attachment.setAttachmentName(name);
            attachmentList.add(attachment);
        }
        if (attachmentDao.insertAttachments(attachmentList) < 0) {
            fileIdList.clear();
        }
        return fileIdList;
    }

    /**
     * 添加备注
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void addNote(String noteContent, String userId, String meetingId) {
        Note note = new Note();
        note.setNoteId(IdGenerator.uuid2());
        note.setUserId(userId);
        note.setMeetingId(meetingId);
        note.setNoteContent(noteContent);
        noteDao.insertNote(note);
    }

    /**
     * 更新决议进度
     * @param params = decisions[{
     *     decisionId:,//决议id
     *     mineId:'',//个人决议进度情况id
     *     finished:''//决议进度完成情况，最大值为100
     * }]
     *
     * @param userId 用户Id
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void updateDecisionProgress(JSONObject params, String userId) {

        JSONArray array = params.getJSONArray("decisions");
        for (int i = 0; i < array.size(); i++) {
            DecisionPerformer decisionPerformer = new DecisionPerformer();
            decisionPerformer.setDecisionPerformerId(array.getJSONObject(i).getString("mineId"));
            decisionPerformer.setFinished(Integer.parseInt(array.getJSONObject(i).getString("finished")));
            decisionPerformerDao.updateDecisionPerformer(decisionPerformer);
            /**
             * 如果个人完成情况等于100,表示完成，那么决议总进度加1。
             */
            if (decisionPerformer.getFinished() == 100) {
                Decision decision = decisionDao.selectDecisionById(array.getJSONObject(i).getString("decisionId"));
                if (decision.getFinished() < decision.getShareNumber()) {
                    decision.setFinished(decision.getFinished() + 1);
                    if (decision.getFinished() == decision.getShareNumber()) {
                        decision.setIsOk(1);
                    }
                    decisionDao.updateDecitionProgress(decision);
                }
            }
        }
    }

    /**
     * 会议检索（模糊查询）
     * @param meetingTitle 会议标题
     * @return
     */
    public List<Meeting> searchMeeting(String meetingTitle, String userId) {
        return meetingDao.searchMeeting("%" + meetingTitle + "%", userId);
    }

    /**
     * 删除会议
     * @param meetingId 会议Id
     */
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED)
    public void delMeeting(String meetingId) {
        meetingDao.delMeetingById(meetingId);
    }

    /**
     * 删除附件
     * @param fileName 附件名称
     * @param fileId 附件id
     * @return
     */
    @Override
    public int delFile(String fileName, String fileId) {
        int result = attachmentDao.deletFileById(fileId);
        if (result > 0) {
            File file = new File(FileUrl.FILELOCAL + fileName);
            file.delete();
        }
        return result;
    }

    public BusinessData getMeetings(Map<String, Object> params) {
        QueryAbstractFilter queryAbstractFilter = new QueryAbstractFilter() {
            @Override
            public void before(RequestData requestData) {
                super.before(requestData);
            }

            @Override
            public void after(BusinessData businessData) {
                super.after(businessData);
            }
        };
        return getList(params, queryAbstractFilter);
    }
}
